package com.ruoyi.web.controller.user;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.system.domain.config.VsDramasConfig;
import com.ruoyi.system.service.config.IVsDramasConfigService;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
 * This file is part of 南阳迈特网络科技有限公司.
 * @company  南阳迈特网络科技有限公司
 * @link     https://www.nymaite.com
 * @document https://product.nymaite.cn
 * @contact  service@nymaite.com
 * @author nymaite
 */
public class QQMailUtil {

    public static void main(String[] args) {
//        String emailAddr = "3202211421@qq.com";
//        // 生成验证码，参数为 随机验证码位数
//        String randomCode = QQMailUtil.generateRandomCode(5);
//
//        sendMail(emailAddr, randomCode);

        System.out.println(System.currentTimeMillis());
    }

    /**
     * 外网邮件发送
     *
     * @param to 收件人邮箱地址 收件人@xx.com
     * @param code 传入的验证码
     */
    public static Boolean sendMail(String to, Integer code, String replace, String value) {
        Map<String, String> map = JSON.parseObject(value, new TypeReference<Map<String, String>>(){});
        String smtpUser = map.get("mail_smtp_user");
        String myEmail = map.get("mail_from");
        String password = map.get("mail_smtp_pass");
        String smtpHost = map.get("mail_smtp_host");
        String smtpPort = map.get("mail_smtp_port");
        // Session对象:
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", smtpHost); // 设置主机地址
        props.setProperty("mail.smtp.port", smtpPort); // SSL默认465,TLS默认587
        // smtp.163.com
        // smtp.qq.com
        // smtp.sina.com
        props.setProperty("mail.smtp.auth", "true");// 认证
        // 2.产生一个用于邮件发送的Session对象
        Session session = Session.getInstance(props);

        // Message对象:
        Message message = new MimeMessage(session);
        // 设置发件人：
        try {
            // 4.设置消息的发送者
            Address fromAddr = new InternetAddress(myEmail);
            message.setFrom(fromAddr);

            // 5.设置消息的接收者 nkpxcloxbtpxdjai
            Address toAddr = new InternetAddress(to);
            // TO 直接发送 CC抄送 BCC密送
            message.setRecipient(MimeMessage.RecipientType.TO, toAddr);

            // 6.设置邮件标题
            message.setSubject("来自 " + smtpUser + " 的安全验证码");
            // 7.设置正文
            String content = replace.replace("{code}", String.valueOf(code));
            message.setContent(content, "text/html;charset=UTF-8");

            // 8.准备发送，得到火箭
            Transport transport = session.getTransport("smtp");
            // 9.设置火箭的发射目标（第三个参数就是你的邮箱授权码）
            //transport.connect("smtp.163.com", "发送者@163.com", "abcdefghabcdefgh");
            transport.connect(smtpHost, myEmail, password);
            // 10.发送
            transport.sendMessage(message, message.getAllRecipients());

            return true;
            // Transport对象:
            // Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String generateRandomCode(int length) {
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length) {
            // 0 ~ s.length()-1
            int index = (new java.util.Random()).nextInt(s.length());
            // 处理重复字符：每个新的随机字符在 sb 中使用indexOf()查找下标值，-1为没找到，即不重复
            Character ch = s.charAt(index);
            if (sb.indexOf(ch.toString()) < 0) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
